package org.elec.mac.gizwits;

import org.elec.mac.constants.Constants;
import org.elec.mac.entity.GizToken;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Bean on 2018/6/2.
 */
@Slf4j
@Component
public class GizApiLogin {

    @Autowired
    private GizWebSocketListener gizWebSocketListener;

    /**
     * API Login
     */
    @Value("${giz.login.url}")
    private String loginUrl;

    @Value("${giz.login.header}")
    private String header;

    @Value("${giz.login.username}")
    private String username;

    @Value("${giz.login.password}")
    private String password;

    private String headerName = "X-Gizwits-Application-Id";

    private String lang = "en";

    /**
     * WebSocket Login
     */
    @Value("${giz.ws.login.url}")
    private String wsUrl;

    @Value("${giz.ws.login.port}")
    private String port;

    @PostConstruct
    public void apiLogin() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS).build();
        try {
            JSONObject json = new JSONObject();
            json.put("username", username);
            json.put("password", password);
            RequestBody body = FormBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString());
            Request request = new Request.Builder().addHeader(headerName, header)
                    .url(loginUrl).post(body).build();
            // 发起网络通信请求
            Response resp = okHttpClient.newCall(request).execute();
            // 响应
            if (resp.isSuccessful()) {
                String responseString = resp.body().string();
                log.info("机智云网关返回内容：" + responseString);
                JSONObject respJson = new JSONObject(responseString);
                String token = respJson.getString("token");
                String uid = respJson.getString("uid");
                long expire_at = respJson.getLong("expire_at");
                GizToken gizToken = new GizToken(token, uid, expire_at);
                Constants.gizToken = gizToken;

                String url = "ws://" + wsUrl + ":" + port + "/ws/app/v1";
                request = new Request.Builder().url(url).build();
                okHttpClient.newWebSocket(request, gizWebSocketListener);
            }
        } catch (Exception ex) {
            log.error("机智云API登录异常 : " + ex);
        }
    }
}
